var 	mysql  = require('mysql');
var connection = mysql.createConnection({
	host     : 'localhost',
	user     : 'flash',
	password : 'flash',
	database : 'iw',
});
var net = require("net"), sys = require('sys');
  
var server = net.createServer(function (stream) {
	stream.setEncoding("utf8");
	stream.on("connect", function () {
		console.log("Connected");
	});
	stream.on("data", function (data) {
		console.log("From Flash = " + data);	
		if(data == '<policy-file-request/>\0') {
/*		policy_xml = 
12         '<?xml version="1.0"?>' +
13         '<!DOCTYPE cross-domain-policy SYSTEM ' +
14         'ww.macromedia.com/xml/dtds/cross-domain-policy.dtd">' +
15         '<cross-domain-policy>' +
16         "<allow-access-from domain='*' to-ports='*'/>" +
17         '</cross-domain-policy>'
18         connection.send(policy_xml); */
			console.log('No policy');
			stream.write("<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>\0");
        }else{
		connection.query("SELECT * FROM twalk_user WHERE wid ='"+ data +"'", function(err, rows, fields) {
			if(rows.length>0){
				stream.write(rows[0].uname +"\0"); 				
				console.log("Send = " + rows[0].uname);
			}else{
				console.log('No result');
			}
		});		
		}		
	});
	stream.on("end", function () {
		console.log('Disconnected');	
		stream.end();
	});
});
server.listen(9001, "127.0.0.1");
function writeCrossDomainFile()
{
     var xml = '<?xml version="1.0"?>';
	 xml += '<!DOCTYPE cross-domain-policy SYSTEM';
     xml += '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">';
     xml += '<cross-domain-policy>';
     xml += '<allow-access-from domain="*" to-ports="*"/>';
     xml += '</cross-domain-policy>'; 
     return xml;
}